package org.sanguine.study.hometasks.first.task.a;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Reader;
import java.util.Arrays;

import org.sanguine.study.hometasks.first.Runner;
import org.sanguine.study.hometasks.first.TaskWorker;

public abstract class CommonStringTask extends Runner implements TaskWorker {
	protected PrintWriter out;
	protected Reader in;
	protected int numberOfItems;
	protected String[] items;

	@Override
	protected TaskWorker getWorkerInstance() {
		return this;
	}
	
	@Override
	public boolean setUp(Reader in, PrintWriter out, String[] args) {
		if (args == null || args.length < 1) return false;
		try {
			numberOfItems = Integer.parseInt(args[0]);
		} catch (NumberFormatException e) {
			System.err.println("Wrong number of items: " + args[0]);
			return false;
		}
		if (numberOfItems < 0) {
			System.err.println("Number of items must be positive: " + args[0]);
			return false;
		}
		if (in == null || out == null) {
			System.err.println("Input or Output streams must be defined");
			return false;
		}
		
		this.in = in;
		this.out = out;
		items = new String[numberOfItems];
		
		return true;
	}

	@Override
	protected void printUsage() {
		System.out.println("USAGE: java -jar 'task-to-run' 'Number-of-Items'");
	}

	protected void readItems() {
		BufferedReader reader = new BufferedReader(in);
		String inString;
		int countOfItems;
		for (countOfItems = 0; countOfItems < numberOfItems; countOfItems++) {
			
			try {
				inString = reader.readLine();
			} catch (IOException e) {
				System.err.println("IOError");
				e.printStackTrace();
				break;
			}
			if (inString == null) {
				System.err.println("Unexpected end of stream");
				break;
			}
			items[countOfItems] = inString;
		}
		if (countOfItems < numberOfItems) {
			items = Arrays.copyOf(items, ++countOfItems);
		}
	}

}
